package com.lemon.smartsafety.ui.activity.fire.item;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.SuperviseCompanyAdd;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.adapter.fire.FireCompanySetAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.SystemUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesHelper;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.dialog.DialogHint;
import com.lemon.smartsafety.view.list.ListRefreshView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class FirefightingCompanySearchActivity extends NewBaseActivity {


    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.txt_search)
    TextView txtSearch;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.listView)
    ListRefreshView listView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;


    private FireCompanySetAdapter fireCompanySetAdapter;
    private DialogHint dialogHint;


    private String strSearch = "";
    private List<SuperviseCompanyAdd> mList;
    private List<SuperviseCompanyAdd> superviseCompanyAddList;

    //是否是扩大搜索
    private boolean isAllSearch = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void getBundleArgs() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_firefighting_company_search;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("监督单位设置");
    }

    @Override
    protected void initView() {
        dialogHint = new DialogHint(mActivity);

        mList = new ArrayList<>();
        fireCompanySetAdapter = new FireCompanySetAdapter(mActivity, mList);
        fireCompanySetAdapter.setBack(new FireCompanySetAdapter.CallBackInterface() {
            @Override
            public void callBackFunction(final int item) {
                getConfirmDialog("确定添加单位(" + mList.get(item).getCompanyName() + ")", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            //添加
                            addCompanyHttp(mList.get(item),item);
                        }
                    }
                }).show();

            }
        });
        listView.setAdapter(fireCompanySetAdapter);

        initSwipRefresh(swipeLayout);
        initLoadeRefresh(listView);

    }

    @Override
    protected void initHttp() {
        initList();
    }

    @Override
    protected void initList() {
        listView.setIsload(true);
        current_page = 1;
        //httpList();
        if (isAllSearch) {
            httpAllSearchList();
        } else {
            httpList();
        }
    }

    @Override
    protected void loadList() {
        if (mList.size() % page_size == 0) {
            current_page = current_page + 1;
            if (isAllSearch) {
                httpAllSearchList();
            } else {
                httpList();
            }
        } else {
            showUpLoad(false, listView);
            listView.setIsload(false);
            ToastUtil.show("没有更多数据了");
        }
    }

    @Override
    protected void refreshView() {

        if (current_page == 1 && CommonUtil.listIsEmpty(superviseCompanyAddList)) {
            showSpecialSearchView();
        } else {
            if (current_page == 1) {
                mList.clear();
            }

            mList.addAll(superviseCompanyAddList);
            errorView("");
            fireCompanySetAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void callFinish() {
        mActivity.finish();
    }

    @OnClick({R.id.txt_search})
    public void onButtonClick(View v) {
        switch (v.getId()) {
            case R.id.txt_search:
                LogUtils.LOGE(txtSearch.getText().toString());

                mList.clear();
                current_page = 1;
                strSearch = etSearch.getText().toString().trim();
                httpList();
                SystemUtil.HideKeyboard(mActivity);
                break;
            default:
                break;
        }
    }


    /**
     * 错误的情况下 刷新
     */
    public void errorView(String title) {

        try {
            if (CommonUtil.listIsEmpty(mList)) {
                viewFireCompanyNone.setVisibility(View.VISIBLE);
                showSwipLayout(swipeLayout,false);
                //是否是扩大搜索
                if (!isAllSearch) {
                    viewFireCompanyNone.setTxt_imgVisible(false);
                    if (CommonUtil.strIsEmpty(title)) {
                        viewFireCompanyNone.setTitle("");
                        viewFireCompanyNone.setSearch("");
                    } else {
                        viewFireCompanyNone.setTitle(title);
                        viewFireCompanyNone.setSearch("重试");
                    }
                    viewFireCompanyNone.setContent("");
                    viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                        @Override
                        public void click() {
                            mList.clear();
                            current_page = 1;
                            strSearch = etSearch.getText().toString().trim();
                            httpList();
                        }
                    });
    
                } else {
                    viewFireCompanyNone.setTxt_imgVisible(true);
                    viewFireCompanyNone.setTitle("没有搜索到匹配的记录");
                    viewFireCompanyNone.setContent("您可以尝试在");
                    viewFireCompanyNone.setSearch("全市范围内搜索");
                    viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                        @Override
                        public void click() {
    
                            LogUtils.LOGE("扩大搜索");
                            mList.clear();
                            current_page = 1;
                            strSearch = etSearch.getText().toString().trim();
                            httpAllSearchList();
    
                        }
                    });
    
                }
    
            } else {
                viewFireCompanyNone.setVisibility(View.GONE);
                showSwipLayout(swipeLayout,true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 一般搜索
     */
    private void httpList() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("page_size", String.valueOf(page_size));
        params.put("current_page", String.valueOf(current_page));

        params.put("keywords", strSearch);

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_supervise_add), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                superviseCompanyAddList = mGson.fromJson(mGson.toJson(baseMode.getResult()), new TypeToken<List<SuperviseCompanyAdd>>() {
                                }.getType());
                                refreshView();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else if (baseMode.getCode().equals("1003")) {
                            if (current_page == 1) {
                                showSpecialSearchView();
                            } else {
                                ToastUtil.show(baseMode.getMsg());
                                errorView(baseMode.getMsg());
                            }
                        } else {
                            if (current_page == 1) {
                                showSpecialSearchView();
                            } else {
                                ToastUtil.show(baseMode.getMsg());
                                errorView(baseMode.getMsg());
                            }
                        }
                        fireCompanySetAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }


    /**
     * 扩大搜索
     */
    private void showSpecialSearchView() {

        mList.clear();
        current_page = 1;
        fireCompanySetAdapter.notifyDataSetChanged();
        isAllSearch = true;

        errorView("");
    }


    /**
     * 扩大搜索
     */
    private void httpAllSearchList() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("page_size", String.valueOf(page_size));
        params.put("current_page", String.valueOf(current_page));
        params.put("total_company", String.valueOf(10));

        params.put("keywords", strSearch);

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_supervise_all_company), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                superviseCompanyAddList = mGson.fromJson(mGson.toJson(baseMode.getResult()), new TypeToken<List<SuperviseCompanyAdd>>() {
                                }.getType());
                                refreshView();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else if (baseMode.getCode().equals("1003")) {
                            if (current_page == 1) {
                                isAllSearch = false;
                            }
                            ToastUtil.show(baseMode.getMsg());
                            errorView(baseMode.getMsg());
                        } else {
                            if (current_page == 1) {
                                isAllSearch = false;
                            }
                            ToastUtil.show(baseMode.getMsg());
                            errorView(baseMode.getMsg());
                        }
                        fireCompanySetAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }


    /**
     * 新增 某项公司
     */
    public void addCompanyHttp(SuperviseCompanyAdd superviseCompanyAdd, final int positon) {
        LemonRequestParams params = new LemonRequestParams("user_company_relation", "relation_id", "");
        params.put("handler", "com.lemon.supervise.UserCompanyRelationAction");
        params.put("op", "edit_user_company_relation");

        params.put("txtCompanyCode", superviseCompanyAdd.getCompanyCode(), Field.TYPE_STRING);
        params.put("txtUserId", new SharedPreferencesHelper(IApplication.context()).getUserId(), Field.TYPE_STRING);
        params.put("_no_html", "1");

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Add_fire_company), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            ToastUtils.toastMsg(baseMode.getMsg());
                            //mHUDUtil.showDoneTip(baseMode.getMsg());
                            mList.remove(positon);
                            fireCompanySetAdapter.notifyDataSetInvalidated();

                            initList();
                            AppService.getBus().post(new RefreshViewEntity(FirefightingCompanySetActivity.class.getName()));
                        } else {
                            mHUDUtil.showErrorTip(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        //刷新顶部
        AppService.getBus().post(new RefreshViewEntity(FirefightingCompanySetActivity.REFRESH_TOP_TAG));

    }
}
